package com.riant.demo.utils;

import com.riant.demo.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname HtmlParseUtil
 * @Description TODO
 * @Date 2021/7/13 0:19
 * @Created by 张斌
 */
@Component
public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {
        //获取请求
        String keywords="java";
        List<Content> contents = parseJDGoods(keywords);
        System.out.println(contents.toString());

    }

    public static List<Content> parseJDGoods(String keywords) throws IOException {
        String url="https://search.jd.com/Search?keyword=" + keywords;
        //String url="https://search.jd.com/Search?keyword=java";
        //解析网页，jsoup返回的document就是浏览器document对象
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        //System.out.println(element.html());
        //获取所有的li元素
        Elements elements = element.getElementsByTag("li");
        ArrayList<Content> goodsList=new ArrayList<>();
        for (Element el : elements) {
            String p_img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String p_price = el.getElementsByClass("p-price").eq(0).text();
            String p_name = el.getElementsByClass("p-name").eq(0).text();
//            System.out.println("================================");
//            System.out.println(p_img);
//            System.out.println(p_price);
//            System.out.println(p_name);
            Content content = new Content();
            content.setTitle(p_name);
            content.setImg(p_img);
            content.setPrice(p_price);
            goodsList.add(content);
        }
        return goodsList;
    }
//    //爬取数据
//    public List<Content> parseJD(String keywords) throws IOException{
//        String url = "https://search.jd.com/Search?keyword=" + keywords + "&enc=utf-8";
//        //解析网页，Jsoup返回的document对象就是浏览器对象
//        Document document = Jsoup.parse(new URL(new String(url.getBytes(),"utf-8")), 30000);
//        //在JS中可以使用的方法,这里都能用
//        Element element = document.getElementById("J_goodsList");
//        //System.out.println(element.html());
//        Elements elements = element.getElementsByTag("li");
//
//        List<Content> goodsList = new ArrayList<>();
//        for (Element e : elements) {
//            String img = e.getElementsByTag("img").eq(0).attr("data-lazy-img");
//            String price = e.getElementsByClass("p-price").eq(0).text();
//            String title = e.getElementsByClass("p-name").eq(0).text();
//
//            goodsList.add(new Content(title,img,price));
//        }
//        return goodsList;
//    }
}
